package com.module.ble.repo

import com.common.base.app.extras.no
import com.module.ble.db.HealthExaManager
import com.module.ble.db.table.UserHealthIntegratedData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/3/25
 * <p>
 * 描述：仓库类，健康综合的数据操作都在此类中进行，数据库的增、删、改、查操作
 * <p> 暂时没用到
 * 修订历史：
 */
class HealthIntegratedDataRepo private constructor() {

    private val refreshTrigger = MutableStateFlow(0)

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { HealthIntegratedDataRepo() }
    }

    private val dao = HealthExaManager.mHealthIntegratedDataDao

    private val scope = CoroutineScope(Dispatchers.IO)

    /**
     * 查找所有数据
     */
    fun findAll(): List<UserHealthIntegratedData>? {
        //数据库查找所有数据
        return dao?.findAll()
    }

    /**
     * 根据时间查找数据
     */
    fun findByTime(time : Long): UserHealthIntegratedData? {
        //数据库查找所有数据
        return dao?.findByTime(time)
    }

    /**
     * 查找所有数据
     */
    @OptIn(ExperimentalCoroutinesApi::class)
    fun findAllFlow(): Flow<List<UserHealthIntegratedData>> = refreshTrigger.flatMapLatest { dao?.findLatestDayFlow() ?: flowOf(emptyList())}

    /**
     * 根据时间范围查询数据
     */
    fun findByTimeRange(startTime:Long, endTime:Long): List<UserHealthIntegratedData>? {
        return dao?.findByTimeRange(startTime,endTime)
    }

    /**
     * 查找所有数据
     */
    @OptIn(ExperimentalCoroutinesApi::class)
    fun findByTimeRangeFlow(startTime:Long, endTime:Long): Flow<List<UserHealthIntegratedData>> = refreshTrigger.flatMapLatest { dao?.findByTimeRangeFlow(startTime,endTime) ?: flowOf(emptyList())}

    /**
     * 插入数据
     */
    fun add2DB(data: UserHealthIntegratedData?) {
        data?.let { dataIt->
            scope.launch {
                dao?.insert(dataIt)
            }
        }
    }

    suspend fun add2DBAndFetch(data: UserHealthIntegratedData?): List<UserHealthIntegratedData>? {
        data?.let { dataIt->
            scope.launch {
                dao?.insert(dataIt)
            }
        }
        return dao?.findAll()
    }

    /**
     * 插入数据
     */
    fun add2DB(mList: List<UserHealthIntegratedData>) {
        mList.isEmpty().no {
            scope.launch {
                dao?.insert(mList)
            }
        }
    }

    fun insert(batch: UserHealthIntegratedData) {
        scope.launch {
            dao?.insert(batch)
        }
    }

    fun insertDistinct(mList: List<UserHealthIntegratedData>, batchSize: Int = 500) {
        if (mList.isNullOrEmpty()) return
        scope.launch {
            // 分批处理
            mList.chunked(batchSize).forEach { batch ->
                dao?.insert(batch) // 直接插入整个批次
            }
        }
    }

    /**
     * 删除数据库中数据
     */
    private fun del2DB(data: UserHealthIntegratedData?) {
        data?.let { dataIt->
            scope.launch {
                dao?.delete(dataIt)
            }
        }
    }

    /**
     * 删除数据库中所有数据
     */
     fun deleteAll() {
            scope.launch {
                dao?.deleteAll()
            }
    }

    /**
     * 自动触发 Flow 的更新，进而更新 LiveData
     */
    fun refreshData() {
        refreshTrigger.value += 1
    }
}